package com.tczs.server.util;

import com.tczs.web.util.StreamUtil;
import org.apache.log4j.Logger;

import java.io.*;

public class FileUtil {
    private static Logger logger = Logger.getLogger(FileUtil.class);

    /**
     * file 转 bute[]数组
     * @param filePath
     * @return
     */
    public static byte[] toByteArray(String filePath){
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = new FileInputStream(filePath);
            out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024 * 4];
            int n = 0;
            while ((n = in.read(buffer)) != -1) {
                out.write(buffer, 0, n);
            }
        } catch (Exception e) {
            logger.error("file convert byte[] is error! filePath: "+filePath,e);
        }finally {
            StreamUtil.close(out);
            StreamUtil.close(in);
        }
        return out.toByteArray();
    }

    /**
     * 如果不存在，则新建。
     * 存在，则追加内容
     * @param txtPath 文件路径
     * @param content 写入内容
     */
    public static void writeTxt(String txtPath,String content){
        FileOutputStream fileOutputStream = null;
        File file = new File(txtPath);
        try {
            if(file.exists()){
                //判断文件是否存在，如果不存在就新建一个txt
                file.createNewFile();
            }
            fileOutputStream = new FileOutputStream(file,true);
            fileOutputStream.write(content.getBytes());
            fileOutputStream.flush();
        } catch (IOException e) {
            logger.error("write content is error",e);
        } finally {
            StreamUtil.close(fileOutputStream);
        }
    }
}
